<template>
	<signPreview
		v-if="isSign"
		:applyId="applyIdFromCommit"
		pageSourceCode="deliveryFinanceTable"
		:finType="finType"
	></signPreview>
	<div
		v-else
		:class="['m-window','applyOrderTable-col',{'opts-hidden':isSubmitApplyTable}]"
		v-loading="loading"
		element-loading-text="数据加载中"
	>
		<el-row :gutter="10" class="header-btns-col">
			<el-col :span="2">
				<el-button type="primary" @click="goBack">返回</el-button>
			</el-col>
		</el-row>
		<el-row :gutter="10" class="footer-btns-col" v-show="!isSubmitApplyTable && !loading">
			<el-col :span="2">
				<el-button type="primary" @click="submit">提交</el-button>
			</el-col>
		</el-row>
		<!-- 融资申请表 -->
		<el-row>
			<el-col :span="23" class="checking-table" v-if="true">
				<label>关联订单</label>
				<div class="opts-col" v-show="!isSubmitApplyTable">
					<a
						href="javasript:;"
						class="hit"
						style="margin-right:18px;"
						@click="addLetter"
						v-show="showAddBtn"
					>添加</a>
					<a href="javasript:;" class="hit" @click="delLetter">删除</a>
				</div>
				<ag-grid-vue
					class="ag-theme-balham ag-table"
					:gridOptions="applyGridOptions"
					:columnDefs="applyColumnDefs"
					:rowData="applyRowData"
					v-loading="applyLoading"
				></ag-grid-vue>
			</el-col>
			<el-col :span="23" class="checking-table" v-if="false">
				<el-tabs type="card" class="applyDetail-tabs">
					<el-tab-pane label="关联订单" name="0">
						<ag-grid-vue
							class="ag-theme-balham ag-table"
							:gridOptions="applyGridOptions"
							:columnDefs="applyColumnDefs"
							:rowData="applyRowData"
							v-loading="applyLoading"
						></ag-grid-vue>
					</el-tab-pane>
				</el-tabs>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="12">
				<el-form :v-model="applyShortTableForm" ref="applyShortTableForm">
					<el-form-item>
						<table class="emphasis-table">
							<tr>
								<th>流程编号：</th>
								<td class="hit font-underline">{{applyShortTableForm.item_no}}</td>
							</tr>
							<tr>
								<th>供应商名称：</th>
								<td>{{applyShortTableForm.cust_name}}</td>
							</tr>
							<tr>
								<th>实际控制人：</th>
								<td>{{applyShortTableForm.realController}}</td>
							</tr>
							<tr>
								<th>收款账户户名：</th>
								<td>{{name}}</td>
							</tr>
							<tr>
								<th>收款账户账号：</th>
								<td>{{bankNo}}</td>
							</tr>
							<tr>
								<th>收款账户开户行：</th>
								<td>{{bank}}</td>
							</tr>
							<tr>
								<th>微信：</th>
								<td>{{applyShortTableForm.custSrmWechat}}</td>
							</tr>
							<tr>
								<th>邮箱：</th>
								<td>{{applyShortTableForm.custSrmEmail}}</td>
							</tr>
							<tr>
								<th>融资金额：</th>
								<td>{{getFormatApplyAmt}} 元</td>
							</tr>
							<tr>
								<th>融资产品：</th>
								<td>{{applyShortTableForm.fin_type}}</td>
							</tr>
							<tr>
								<th>
									<div>
										<span style="color:red">*</span>
										<span>融资开始日期</span>
									</div>
								</th>
								<td @click="datePickerFocus">
									<el-date-picker
										v-model="applyShortTableForm.apply_date"
										type="date"
										placeholder="选择日期"
										value-format="yyyy-MM-dd"
										:picker-options="pickerOptionsBegin"
										:readonly="startDateReadeOnly"
									></el-date-picker>
								</td>
							</tr>
							<tr>
								<th>
									<div>
										<span style="color:red">*</span>
										<span>融资到期日期</span>
									</div>
								</th>
								<td class="endDatePicker" @click="datePickerFocus">
									<!-- <span style="display:inline-block;width:120px;">{{applyShortTableForm.prepayback_date}}</span> -->
									<el-date-picker
										v-model="applyShortTableForm.prepayback_date"
										type="date"
										placeholder="选择日期"
										value-format="yyyy-MM-dd"
										:picker-options="pickerOptionsEnd"
										:readonly="endDateReadeOnly"
									></el-date-picker>
									<el-popover
										placement="top-start"
										title="说明"
										width="220"
										trigger="hover"
										:content="tagContent"
									>
										<span slot="reference">
											<i class="el-icon-info"></i>
										</span>
									</el-popover>
								</td>
							</tr>
							<tr>
								<th>融资天数：</th>
								<td>{{applyShortTableForm.dayAmount||0}}天</td>
							</tr>
							<tr>
								<th>融资订单数量：</th>
								<td>{{applyRowData.length}}</td>
							</tr>
							<tr>
								<th>服务费率（含税）：</th>
								<td>
									<span>{{showRate}}</span>
									<el-popover placement="right" title="利率说明" width="280" trigger="hover">
										<div>
											<p style="padding:5px 0">融资方式：{{mode=='order'?'金单宝':'金货宝'}}</p>
											<p style="padding:5px 0">还款方式：预扣利息服务费,到期还本</p>
											<el-table :data="gridData" border size="small">
												<el-table-column width="139" property="date" label="融资天数"></el-table-column>
												<el-table-column property="rate" label="融资利率"></el-table-column>
											</el-table>
										</div>
										<span slot="reference">
											<i class="el-icon-info"></i>
										</span>
									</el-popover>
								</td>
							</tr>
							<tr>
								<th>预扣服务费（含税）：</th>
								<td>{{applyShortTableForm.preDeductAmount}} 元</td>
							</tr>
							<tr>
								<th>到账金额：</th>
								<td>{{applyShortTableForm.arrivalAmount}} 元</td>
							</tr>
							<tr>
								<th>还款金额：</th>
								<td>{{getFormatApplyAmt}} 元</td>
							</tr>
							<tr>
								<th>金融客服：</th>
								<td>{{applyShortTableForm.apply_user}}</td>
							</tr>
							<tr>
								<th>客服电话：</th>
								<td>{{applyShortTableForm.apply_phone}}</td>
							</tr>
						</table>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
		<el-row v-show="fileList.length > 0&&currentActs.includes(currentAct)" style="margin-top:20px;">
			<el-col :span="24">
				<label style="font-size: 12px;font-weight: 600;">相关附件</label>
				<ul class="accessory">
					<li v-for="(v,i) in fileList" :key="i">
						<span>{{v.name}}</span>
						<el-button plain size="mini" type="primary" @click="downloadFiles(v)">下载</el-button>
					</li>
				</ul>
			</el-col>
		</el-row>
		<el-row v-show="returnReason!=''">
			<el-col :span="23">
				<label style="color:red;">退回原因</label>
				<div class="returnReason">{{returnReason}}</div>
			</el-col>
		</el-row>
		<!-- 添加订单 模态框 -->
		<el-dialog title="订单列表" :visible.sync="assemblyModel" v-dialogDrag width="75%">
			<el-row :gutter="10" class="m-condition">
				<el-col :span="6">
					<el-select value-key="id" v-model="orderState" placeholder="订单融资状态">
						<el-option
							v-for="item in stateOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						></el-option>
					</el-select>
				</el-col>
				<el-col :span="3" :offset="15">
					<el-button type="primary" @click="searchLetter">搜索</el-button>
				</el-col>
			</el-row>
			<el-row>
				<el-col>
					<ag-grid-vue
						class="m-agTableModel ag-theme-balham"
						:gridOptions="checkingGridOptions"
						:columnDefs="checkingColumnDefs"
						:rowData="checkingRowData"
						v-loading="checkingLoading"
						overlayNoRowsTemplate="&nbsp;"
					></ag-grid-vue>
				</el-col>
			</el-row>
			<el-row type="flex" justify="center">
				<el-col :span="4">
					<el-button type="primary" style="margin:20px 0;" @click="saveLetter">确认</el-button>
				</el-col>
			</el-row>
		</el-dialog>
		<!-- 查看订单详情弹窗 -->
		<el-dialog
			title="订单详情"
			:visible.sync="detailModel"
			v-dialogDrag
			width="75%"
			class="order-detail-dialog"
		>
			<div v-loading="orderDetailLoading">
				<el-row class="detail-row" :gutter="20">
					<el-col :span="8">
						<div class="detail-item">
							<label style="width:70px">订单号:</label>
							<span>{{orderDetailData.purOrdNo||''}}</span>
						</div>
					</el-col>
					<el-col :span="9">
						<div class="detail-item" v-if="mode=='order'">
							<label style="width:120px">最早约定交货日期:</label>
							<span>{{orderDetailData.oldestDeliveryDate}}</span>
						</div>
						<div class="detail-item" v-else>
							<label style="width:120px">最早入库日期:</label>
							<span>{{orderDetailData.earliestInstockDate}}</span>
						</div>
					</el-col>
					<el-col :span="7">
						<div class="detail-item" v-if="mode=='delivery'">
							<label style="width:70px">订单状态:</label>
							<span>{{orderDetailData.orderStatus}}</span>
						</div>
						<div class="detail-item" v-else>
							<label style="width:70px">订单状态:</label>
							<span>{{orderDetailData.billStateDesc}}</span>
						</div>
					</el-col>
				</el-row>
				<el-row class="detail-row" :gutter="20">
					<el-col :span="8">
						<div class="detail-item" v-if="mode=='delivery'">
							<label style="width:70px">订单金额:</label>
							<span>{{orderDetailData.orderPrice}}</span>
						</div>
						<div class="detail-item" v-else>
							<label style="width:70px">订单金额:</label>
							<span>{{orderDetailData.orderMoney}}</span>
						</div>
					</el-col>
					<el-col :span="9">
						<div class="detail-item" v-if="mode=='order'">
							<label style="width:120px">订单金额的40%:</label>
							<span>{{orderDetailData.orderMoneyPart}}</span>
						</div>
						<div class="detail-item" v-else>
							<label style="width:120px">入库金额:</label>
							<span>{{orderDetailData.instockPrice}}</span>
						</div>
					</el-col>
					<el-col :span="7" v-if="mode=='delivery'">
						<div class="detail-item">
							<label style="width:70px">入库次数:</label>
							<span>{{`${orderDetailData.instockNum}次`}}</span>
						</div>
					</el-col>
				</el-row>
				<div class="historyRecord">
					<p>{{mode=='order'?'订单变更记录':'订单入库记录'}}</p>
					<ag-grid-vue
						class="m-agTableModel ag-theme-balham"
						:gridOptions="changeGridOptions"
						:columnDefs="changeColumnDefs"
						:rowData="changeRowData"
					></ag-grid-vue>
				</div>
				<div class="historyRecord">
					<p>历史融资记录</p>
					<ag-grid-vue
						class="m-agTableModel ag-theme-balham"
						:gridOptions="historyGridOptions"
						:columnDefs="historyColumnDefs"
						:rowData="historyRowData"
					></ag-grid-vue>
				</div>
			</div>
		</el-dialog>
	</div>
</template>
<style>
.msg-hint .el-message-box__message p {
	text-align: left !important;
	word-break: break-all;
}
</style>

<style lang="less" scoped>
.applyOrderTable-col {
	height: 100%;
	padding-top: 50px !important;
	overflow-y: auto;
	overflow-x: hidden;
	&:after {
		display: block;
		height: 100px;
		content: "";
	}
	.returnReason {
		border: 1px solid #eee;
		padding: 5px;
		min-height: 100px;
		margin-top: 5px;
	}
	.accessory {
		li {
			line-height: 25px;
			span {
				color: #409eff;
				cursor: pointer;
			}
			/deep/.el-button.el-button--mini {
				height: 20px !important;
				width: 50px !important;
				line-height: 20px !important;
				padding: 0 !important;
				margin-left: 20px;
			}
		}
	}
	.footer-btns-col,
	.header-btns-col {
		position: fixed;
		height: 60px;
		width: 100%;
		bottom: 0;
		z-index: 10;
		margin-left: -10px !important;
		box-sizing: border-box;
		display: flex;
		justify-content: center;
		align-items: center;
		background: #fff;
		padding: 10px 0;
		border-top: 1px solid #eee;
		/deep/ .el-button {
			margin-left: -84px;
		}
	}
	.header-btns-col {
		top: 0;
		justify-content: flex-start;
		border-top: none;
		border-bottom: 1px solid #eee;
		margin-top: 100px;
		/deep/ .el-button {
			margin-left: 8px;
		}
	}
	.hit {
		color: #409eff !important;
	}
	.emphasis-table {
		width: 100%;
		margin-top: 10px;
		.endDatePicker {
			/deep/.el-date-editor {
				width: 90%;
			}
		}
		.font-underline {
			text-decoration: underline;
		}
		tr {
			&:nth-child(even) th,
			&:nth-child(even) td {
				background: #f9fafa;
			}
			td,
			th {
				border: 1px solid #eee;
				padding: 0 10px;
				height: 35px;
				line-height: 35px;
				text-align: right;
				width: 50%;
			}
			td {
				text-align: left;
				& /deep/.el-input {
					.el-input__inner {
						border: none !important;
						outline-style: none !important;
						height: 35px;
						line-height: 35px;
						margin-left: -10px;
					}
					.el-input__icon {
						margin-left: -10px;
						margin-top: -5px;
					}
				}
			}
		}
	}
	.checking-table {
		& label {
			font-size: 12px;
			font-weight: 600;
		}
		.ag-table {
			height: 200px;
			width: 100%;
			margin-top: 8px;
		}
		.opts-col {
			float: right;
		}
	}
	.historyRecord {
		p {
			margin: 10px 0;
			font-weight: bold;
			font-size: 12px;
		}
		.m-agTableModel {
			height: 190px;
			/deep/.ag-tool-panel {
				display: none;
			}
		}
	}
	.applyDetail-tabs {
		min-height: 280px;
		/deep/ .el-tabs__content {
			left: 0;
			top: 20px;
			.ag-table {
				height: 220px;
			}
		}
		/deep/ .el-tabs__item.is-top.is-active {
			background: #409eff;
			color: #fff;
		}
	}
	.order-detail-dialog {
		/deep/.el-dialog__body {
			overflow-y: auto;
			overflow-x: hidden;
			max-height: 520px;
			padding-bottom: 20px;
		}
		.detail-row {
			.detail-item {
				padding: 4px;
				label {
					display: inline-block;
					// text-align: right;
				}
			}
		}
	}
}
</style>
<script>
import Pagination from "@/components/pagination.vue";
import gridOptions from "lesso-common/public/gridOptions";
import signPreview from "@/components/SRM/pageComponents/signPreview";
import buttonLink from "@/components/buttonLink.js"
import downloadFile from "@/util/fileDownload.js";
import Msg from "@/public/message"
import {
	formatRate,
	formatPrice,
	dateDiff,
	getSpecifyDate,
	numberMul,
	numberSub
} from "@/util/format.js";
import {
	mapState,
	mapActions
} from "vuex";
/**
 * @group financeManager
 * 金单宝/金货宝提交申请详情
*/
export default {
	name: "deliveryFinanceTable",
	props: {
		// 申请单Id
		applyId: {
			type: String,
			required: false
		},
		// 我的申请进入的申请单Id
		applyListApplyId: {
			type: String
		},
		// 当前流程节点
		currentAct: {
			type: String,
		},
		// 融资产品类型
		mode: {
			// "order"/"delivery"
			type: String,
			required: true
		},
		// 融资申请单编号
		flowNumber: {
			type: String
		},
	},
	data () {
		return {
			detailModel: false,//查看订单详情弹窗
			isSearch: false,
			returnReason: '',
			loading: false,
			bankNo: '',
			bank: '',
			name: '',
			wfType: '', //流程类型，1：天进宝300万以下  2：天进宝300万以上
			applyIdFromCommit: '', //流程Id
			fromPage: '',
			custInf: this.$store.state.supplyChainFinance.custInf, //获取供应商信息
			currentPage: 1,
			isSign: false,
			assemblyModel: false,
			listArray: [],
			applyShortTableForm: {
				id: "",
				item_no: "",
				cust_name: "",
				apply_amt: 0,
				fin_type: 0,
				apply_date: "",
				dayAmount: 0,
				service_rate: 0,
				preDeductAmount: 0,
				arrivalAmount: 0,
				apply_user: "",
				apply_phone: "",
				prepayback_date: "",
				custSrmEmail: "",
				custSrmWechat: "",
				realController: ''
			},
			// searchParams: {
			//   pageNumber: 1
			// },
			checkingTotal: 50,
			checkingGridOptions: {},
			checkingColumnDefs: [],
			checkingRowData: [],
			checkingLoading: false,
			applyTotal: 50,
			applyGridOptions: {},
			applyColumnDefs: [],
			applyRowData: [],
			applyLoading: false,
			pageListParams: {
				entity: {},
				current: 1,
				size: 10
			},
			orderState: 1,//订单融资状态
			stateOptions: [
				{ value: 1, label: '可融资订单' },
				{ value: 2, label: '不可融资订单' },
				{ value: 3, label: '全部' }
			],
			// 订单变更表格数据
			changeRowData: [],
			// 历史融资记录数据
			historyRowData: [],
			// 日期选择器只读
			startDateReadeOnly: true,
			endDateReadeOnly: true,
			whitelist: [],
			blacklist: [],
			orderDetailLoading: false,
			// 订单详情数据
			orderDetailData: {},
			fileList: [],
			currentActs: ["联塑金融审批", "已完成", "已退回", "已撤销", "已失效", "供应商还款"],
			// 显示添加按钮
			showAddBtn: true,
			// 已关联订单可融资总金额
			currentMoney: 0,
			maxEndDate: '',
			finType: ''
		};
	},
	created () {
		let that = this
		document.onkeyup = function (e) {
			if (window.event) {
				e = window.event
			}
			var code = e.charCode || e.keyCode;
			if (code == 13) {
				that.searchLetter()
			}
		}
		this.getEsignAccountByCustId()
		this.applyGridOptions = {
			context: {
				componentParent: this
			},
			...gridOptions()
		}
		this.checkingGridOptions = {
			...gridOptions()
		};
		// 订单变更历史表格配置
		this.changeGridOptions = gridOptions()
		// 订单融资历史表格配置
		this.historyGridOptions = gridOptions()
		// 订单变更列配置
		let changeColumnDefs = [
			{
				headerName: "行号",
				field: "mxNum",
				width: 80
			},
			{
				headerName: "变更内容",
				field: "fieldName",
				width: 120
			},
			{
				headerName: "旧值",
				field: "oldValue",
				width: 100
			},
			{
				headerName: "新值",
				field: "newValue",
				width: 100
			},
			{
				headerName: "变更时间",
				field: "createDate",
				width: 160,
			},
			{
				headerName: "确认人",
				field: "modifyer",
				width: 120,
				tooltipField: 'modifyer'
			},
			{
				headerName: "确认时间",
				field: "modifyDate",
				width: 160,
			},
		]
		// 订单入库记录列配置
		let instockColumnDefs = [
			{
				headerName: "行号",
				field: "purOrdMxNo",
				width: 90
			},
			{
				headerName: "入库日期",
				field: "instockDate",
				width: 120,
				valueFormatter: params => {
					return this.$utils.dateFormat('yyyy-MM-dd', params.value)
				}
			},
			{
				headerName: "入库金额",
				field: "instockPrice",
				width: 120,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "入库数量",
				field: "instockAmount",
				width: 120
			}
		]
		// 历史融资变更列配置
		this.historyColumnDefs = [
			{
				headerName: "融资申请号",
				field: "itemNo",
				width: 140,
			},
			{
				headerName: "融资日期",
				field: "payDate",
				width: 140,
				valueFormatter: params => {
					return this.$utils.dateFormat('yyyy-MM-dd', params.value)
				}
			},
			{
				headerName: "融资到期",
				field: "paybackDate",
				width: 140,
				valueFormatter: params => {
					return this.$utils.dateFormat('yyyy-MM-dd', params.value)
				}
			},
			{
				headerName: "融资金额",
				field: "actAmt",
				width: 140,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "申请状态",
				field: "currentAct",
				width: 120,
				valueFormatter: params => {
					return params.value == "供应商还款" ? "待还款" : params.value
				}
			}
		]
		let setCellStyle = (pramas) => {
			const { borrowBalance } = pramas.data
			// 不可融资订单背景置灰且不可选 
			if (!borrowBalance || borrowBalance == 0 || borrowBalance < 0) {
				return { backgroundColor: '#ededed' };
			} else {
				return { backgroundColor: null };
			}
		};
		let setCellStyle2 = (pramas) => {
			const { availableAmount } = pramas.data
			// 不可融资订单背景置灰且不可选   
			if (!availableAmount || availableAmount == 0 || availableAmount < 0) {
				return { backgroundColor: '#ededed' };
			} else {
				return { backgroundColor: null };
			}
		};
		// 订单融添加订单弹窗
		let orderColumnDefs = [
			{
				checkboxSelection: true, //是否显示复选框
				headerCheckboxSelection: true, //是否显示全选框
				headerName: "采购订单号",
				field: "orderNumber",
				width: 200,
				cellStyle: setCellStyle,
			},
			{
				headerName: "订单金额",
				field: "orderMoney",
				width: 120,
				cellStyle: setCellStyle,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "订单日期",
				field: "orderDate",
				width: 120,
				cellStyle: setCellStyle,
				valueFormatter: params => {
					return this.$utils.dateFormat("yyyy-MM-dd", params.value)
				}
			},
			{
				headerName: "最早约定交货日期",
				field: "oldestDeliveryDate",
				width: 160,
				cellStyle: setCellStyle,
				valueFormatter: params => {
					return this.$utils.dateFormat("yyyy-MM-dd", params.value)
				}
			},
			{
				headerName: "应付公司",
				field: "companyName",
				width: 160,
				cellStyle: setCellStyle,
				tooltipField: "companyName"
			},
			{
				headerName: "已融资金额",
				field: "alreadyActBalance",
				width: 110,
				cellStyle: setCellStyle,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "已融占比",
				field: "actBalancePart",
				width: 110,
				cellStyle: setCellStyle,
				// valueFormatter: params => {
				// 	return formatRate(params.value)
				// }
			},
			{
				headerName: "可融金额",
				field: "borrowBalance",
				width: 110,
				cellStyle: setCellStyle,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "融资状态",
				field: "finStateDesc",
				width: 100,
				cellStyle: setCellStyle,
			},
			{
				headerName: "订单状态",
				field: "billStateDesc",
				width: 100,
				cellStyle: setCellStyle
			},
		];
		// 交货融选择订单列配置
		let deliveryColumnDefs = [
			{
				checkboxSelection: true, //是否显示复选框
				headerCheckboxSelection: true, //是否显示全选框
				headerName: "采购订单号",
				field: "purOrdNo",
				cellStyle: setCellStyle2,
				width: 200,
			},
			{
				headerName: "订单金额",
				field: "orderAmount",
				width: 120,
				cellStyle: setCellStyle2,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "交货金额",
				field: "deliveryAmount",
				width: 120,
				cellStyle: setCellStyle2,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "最早交货日期",
				field: "earliestDeliveryDate",
				width: 160,
				cellStyle: setCellStyle2,
				valueFormatter: params => {
					return this.$utils.dateFormat('yyyy-MM-dd', params.value)
				}
			},
			{
				headerName: "应付公司",
				field: "companyName",
				width: 160,
				cellStyle: setCellStyle2,
				tooltipField: "companyName"
			},
			{
				headerName: "已融资金额",
				field: "meltedAmount",
				width: 110,
				cellStyle: setCellStyle2,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "已融占比",
				field: "meltdown",
				width: 110,
				cellStyle: setCellStyle2
			},
			{
				headerName: "可融金额",
				field: "availableAmount",
				width: 110,
				cellStyle: setCellStyle2,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "融资状态",
				field: "financingStatus",
				width: 100,
				cellStyle: setCellStyle2,
				cellRenderer: function (params) {
					if (params.value != undefined && params.value == 0) {
						return "未融";
					} else if (params.value == 1) {
						return "在融";
					}
				}
			},
			{
				headerName: "订单状态",
				field: "orderStatus",
				width: 100,
				cellStyle: setCellStyle2,
				cellRenderer: function (params) {
					if (params.value != undefined && params.value == 3) {
						return "部分交货";
					} else if (params.value == 2) {
						return "未交货";
					} else {
						return "完全交货";
					}
				}
			},
			{
				headerName: "对账状态",
				field: "accountStatus",
				width: 100,
				cellStyle: setCellStyle2,
				cellRenderer: function (params) {
					if (params.value == 1) {
						return "未对账";
					} else if (params.value == 2) {
						return "已对账";
					}
				}
			},
		];
		// 申请融资关联订单列表列配置
		this.applyColumnDefs = [];
		let orderApplyCol = [{
			checkboxSelection: true, //是否显示复选框
			headerCheckboxSelection: true, //是否显示全选框
			cellRenderer: buttonLink,
			headerName: "订单编号",
			width: 205,
			field: "orderNumber"
		},
		{
			headerName: "最早约定交货日期",
			field: "oldestDeliveryDate",
			width: 160,
			valueFormatter: params => {
				return this.$utils.dateFormat("yyyy-MM-dd", params.value)
			}
		},
		{
			headerName: "订单金额",
			field: "orderMoney",
			width: 120,
			valueFormatter: params => {
				return formatPrice(params.value)
			}
		},
		{
			headerName: "可融金额",
			field: "borrowBalance",
			width: 150,
			valueFormatter: params => {
				return formatPrice(params.value)
			}
		},
		{
			headerName: "已融资金额",
			field: "finBalance",
			width: 150,
			valueFormatter: params => {
				const { alreadyActBalance,finBalance, actBalance } = params.node.data
				if (!isNaN(alreadyActBalance)) {
					return formatPrice(alreadyActBalance)
				} else {
					return formatPrice(numberSub(finBalance, actBalance))
				}
			}
		},
		{
			headerName: "本次融资金额",
			field: "actBalance",
			width: 140,
			valueFormatter: params => {
				return formatPrice(params.value)
			}
		}
		];
		let deliveryApplyCol = [{
			checkboxSelection: true, //是否显示复选框
			headerCheckboxSelection: true, //是否显示全选框
			cellRenderer: buttonLink,
			headerName: "订单编号",
			width: 205,
			field: "purOrdNo"
		},
		{
			headerName: "最早交货日期",
			field: "earliestDeliveryDate",
			width: 160,
			valueFormatter: params => {
				return this.$utils.dateFormat("yyyy-MM-dd", params.value)
			}
		},
		{
			headerName: "交货金额",
			field: "deliveryAmount",
			width: 120,
			valueFormatter: params => {
				return formatPrice(params.value)
			}
		},
		{
			headerName: "可融金额",
			field: "availableAmount",
			width: 150,
			valueFormatter: params => {
				return formatPrice(params.value)
			}
		},
		{
			headerName: "已融资金额",
			field: "meltedAmount",
			width: 150,
			valueFormatter: params => {
                if(this.applyListApplyId){
                    const { meltedAmount, actBalance } = params.node.data
                    // 已融资金额减去本次申请金额
                    return formatPrice(numberSub(meltedAmount, actBalance))
                } else {
                    return formatPrice(params.value)
                }
			}
		},
		{
			headerName: "本次融资金额",
			field: "actBalance",
			width: 140,
			valueFormatter: params => {
				return formatPrice(params.value)
			}
		}
		]
		if (this.mode == 'order') {
			this.applyColumnDefs = orderApplyCol
			this.checkingColumnDefs = orderColumnDefs
			this.changeColumnDefs = changeColumnDefs
		} else if (this.mode == 'delivery') {
			this.applyColumnDefs = deliveryApplyCol
			this.checkingColumnDefs = deliveryColumnDefs
			this.changeColumnDefs = instockColumnDefs
		}
		if (this.currentActs.includes(this.currentAct)) {
			this.pageListParams.entity.applyId = this.applyListApplyId;
			this.queryAttachmentInfo()
			if (this.mode == 'delivery') {
				// 获取交货融申请已关联的订单
				this.getRelatedOrderList(this.applyListApplyId)
			} else if (this.mode == 'order') {
				// 获取订单融申请已关联的订单
				this.getOrderFinRelateOrder(this.applyListApplyId)
			}
		}
		this.getDays()
	},
	beforeMount () {
		let that = this;
		this.fromPage = this.supplierApplyList.fromPage;
		let applyMainId = "e0625b2c-47ac-49ab-8b4e-3b6ad4458887"; //申请主表id
		// 1e0911dc-1bcc-42de-9972-07dc5edbe8c4
		if (this.fromPage == "deliveryFinancePreview") {
			//从确认融资页面跳转
			applyMainId = that.applyId;
		} else if (this.fromPage == "applyList") {
			//从申请列表跳转
			applyMainId = that.applyListApplyId;
		}
		// applyMainId = that.applyId || that.applyListApplyId
		if (this.currentAct == '已退回') {
			this.getRefusedActivity(applyMainId)
		}
		if (applyMainId) {
			//获取申请主表信息
			that.$http.getApplyInfo({
				id: applyMainId
			}).then(response => {
				setTimeout(() => {
					that.loading = false
				}, 500)
				if (response.data.code == 200) {
					let data = response.data.rows;
					let prepaybackDate = ''
					if (this.mode == 'order') {
						prepaybackDate = data.paybackDate
					} else {
						prepaybackDate = data.prepaybackDate
					}
					that.applyShortTableForm.id = data.id
					that.applyShortTableForm.item_no = data.itemNo
					that.applyShortTableForm.cust_name = data.custName
					that.applyShortTableForm.apply_amt = data.applyAmt ? data.applyAmt : 0
					that.applyShortTableForm.fin_type = data.finType == 0 ? "天进宝" : data.finType == 1 ? "月有钱" : data.finType == 2 ? '金单宝' : '金货宝'
					that.applyShortTableForm.service_rate = data.serviceRate ? data.serviceRate : 0
					that.applyShortTableForm.apply_user = data.applyUser
					that.applyShortTableForm.apply_phone = data.applyPhone
					that.applyShortTableForm.prepayback_date = prepaybackDate ? prepaybackDate.substring(0, 10) : ''
					that.applyShortTableForm.apply_date = data.applyDate ? data.applyDate.substring(0, 10) : ''
					that.applyShortTableForm.custSrmEmail = data.custSrmEmail
					that.applyShortTableForm.custSrmWechat = data.custSrmWechat
					that.applyShortTableForm.availableAmt = data.availableAmt
					that.applyShortTableForm.realController = data.realController
				} else {
					this.$alert("获取申请表信息失败", {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				}
			})
				.catch(errror => {
					this.loading = false
					this.$alert("查询主表信息失败，请检查网络", {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					})
				});
		}
	},
	methods: {
		...mapActions(["changeTOdo", "changePageCode"]),
		...mapActions(["changeFromPage"]),
        /**
		 * @vuese
		 * 日期选择器获取焦点事件回调
		*/
		datePickerFocus () {
			if (Array.isArray(this.applyRowData) && this.applyRowData.length == 0) {
				Msg.showPopMsg('请先添加您需要关联的订单')
				this.applyShortTableForm.apply_date = ''
				return
			}
		},
		/**
		 * @vuese
		 * 调接口获取当前申请单生成附件信息
		*/
		async queryAttachmentInfo () {
			let param = {
				entity: {
					itemNo: this.flowNumber
				},
				current: 1,
				size: 100
			};
			await this.$http.queryAttachmentInfo(param).then(({ data }) => {
				if (data.code == 200 && data.rows) {
					this.fileList = data.rows.filter((item) => {
						return item.type == 1 || item.type == 0 || item.type == 5
					})
				}
			});
		},
        /**
		 * @vuese
		 * 下载附件
         * @arg 参数V位需要下载的文件信息
		*/
		downloadFiles (v) {
			let path = v.lastPath;
			let fileName = `${v.name}`;
			var group = ''
			if (path.indexOf('SRM') > -1) {
				group = 'SRM'
			} else if (path.indexOf('SIGN') > -1) {
				group = 'SIGN'
			} else if (path.indexOf('TEST') > -1) {
				group = 'TEST'
			} else if (path.indexOf('MES') > -1) {
				group = 'MES'
			}
			let params = {
				'viewPath': group + `${path.split(group)[1]}`,
				'groupName': group,
				'fileName': fileName
			}
			downloadFile(params, fileName + '.pdf')
		},
        /**
		 * @vuese
		 * 获取金单宝当前申请单已关联订单
         * @arg 参数applyId为当前申请单Id
		*/
		getOrderFinRelateOrder (applyId) {
			this.$http.getOrderFinRelatedOrder({ applyId: applyId }).then(({ data }) => {
				if (data.code == 1 || data.code == 200) {
					let rowData = data.rows.list
					this.applyRowData = []
					rowData.forEach(row => {
						this.applyRowData.push({
							...row,
							orderNumber: row.orderNo,
							orderMoney: row.orderBalance,
							oldestDeliveryDate: row.appointmentDate,
							meltedAmount: row.finBalance
						})
					})
				} else {
					this.applyRowData = []
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.applyRowData = []
				Msg.showErrorMsg('获取关联订单数据失败!')
			})
		},
		/**
		 * @vuese
		 * 获取金货宝当前申请单已关联订单
         * @arg 参数applyId为当前申请单Id
		*/
		getRelatedOrderList (applyId) {
			this.$http.getRelatedOrderList({ applyId: applyId }).then(({ data }) => {
				if (data.code == 1) {
					this.applyRowData = []
					// this.applyRowData = data.rows
					data.rows.forEach(el => {
						let rowItem = {
							...el,
							purOrdNo: el.orderNo,
							deliveryAmount: el.instockBalance,
							earliestDeliveryDate: el.instockDate
						}
						this.applyRowData.push(rowItem)
					})
				} else {
					this.applyRowData = []
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				Msg.showErrorMsg('获取关联订单数据失败!')
			})
		},
        /**
		 * @vuese
		 * 限制日期控件日期选择范围只能为工作日
         * @arg 参数time为时间戳格式时间，dateStr为已格式化时间，isBeginDate是否为起始时间
		*/
		datePickerOptions (time, dateStr, isBeginDate) {
			let weeks = time.getDay() //周几？
			// let day = time.getDate() //几号？
			// if (isBeginDate && day < 5 || day > 25) {
			// 	return true
			// }
			if (this.whitelist.includes(dateStr)) {
				return false
			}
			if (this.blacklist.includes(dateStr) || weeks == 6 || weeks == 0) {
				return true
			}
			return false
		},
		/**
		 * @vuese
		 * 获取放假日期
		*/
		async getDays () {
			let that = this
			await this.$http.getDays().then(({ data }) => {
				if (data.code == 200 && data.rows) {
					that.whitelist = data.rows.workdays //工作日
					that.blacklist = data.rows.holidays //假日
				} else {
					this.$alert(`获取数据失败：${data.info}`, {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				}
			}).catch(error => {
				this.$alert('查询日期数据失败，请检查网络！', {
					confirmButtonText: "确定",
					customClass: "alertFailure"
				})
			})
		},
		/**
		 * @vuese
		 * 点击已关联订单订单号回调
         * @arg 参数params为当前行信息
		*/
		setClickValue (params) {
			// this.queryOrderInstock(params.value)
			this.orderDetailLoading = true
			if (this.mode == 'delivery') {
				Promise.all([this.queryOrderInstock(params.value), this.getOrderHistory(params.value)]).then(result => {
					this.orderDetailLoading = false
					const { earliestInstockDate, orderPrice, instockPrice, orderStatus, purOrdNo, instockNum } = result[0]
					this.orderDetailData = {
						purOrdNo,
						instockNum,
						earliestInstockDate: this.$utils.dateFormat("yyyy-MM-dd", earliestInstockDate),
						orderPrice: formatPrice(orderPrice) + '元',
						instockPrice: formatPrice(instockPrice) + '元',
						orderStatus: orderStatus == 2 ? '未交货' : orderStatus == 3 ? '部分交货' : '完全交货'
					}
					this.changeRowData = result[0].instockmxs
					this.historyRowData = result[1]
				}).catch(err => {
					this.orderDetailLoading = false
					Msg.showErrorMsg(err)
				})
			} else if (this.mode == 'order') {
				let { orderId } = params.data
				this.getOrderChangeData(orderId).then(data => {
					this.orderDetailLoading = false
					this.orderDetailData = {
						...data.orderMessage,
						orderMoney: formatPrice(data.orderMessage.orderMoney),
						orderMoneyPart: formatPrice(data.orderMessage.orderMoneyPart),
						oldestDeliveryDate: this.$utils.dateFormat("yyyy-MM-dd", data.orderMessage.oldestDeliveryDate)
					}
					this.changeRowData = data.orderChanges
					this.historyRowData = data.HistoryListDto
				}).catch(err => {
					this.orderDetailLoading = false
					Msg.showErrorMsg(err)
				})
			}
			this.detailModel = true
		},
        /**
		 * @vuese
		 * 获取金货宝已关联订单历史融资记录
         * @arg 参数purOrdNo为订单号
		*/
		getOrderHistory (purOrdNo) {
			let params = {
				purOrdNo: purOrdNo,
				customerId: this.custInf.custId
			}
			return new Promise((resolve, reject) => {
				this.$http.getOrderHostoryList(params).then(({ data }) => {
					if (data.code == 1) {
						resolve(data.rows)
					} else {
						reject(data.info)
					}
				}).catch(err => {
					reject('获取数据失败!')
				})
			})
		},
        /**
		 * @vuese
		 * 获取金货宝已关联订单入库信息
         * @arg 参数purOrdNo为订单号
		*/
		queryOrderInstock (purOrdNo) {
			return new Promise((resolve, reject) => {
				this.$http.reviewOrderDetail({ purOrdNo: purOrdNo }).then(({ data }) => {
					if (data.code == 1) {
						resolve(data.rows)
					} else {
						Msg.showErrorMsg(data.info)
						reject(data.info)
					}
				}).catch(err => {
					Msg.showErrorMsg('获取数据失败!')
					reject('获取数据失败!')
				})
			})
		},
        /**
		 * @vuese
		 * 获取金单宝已关联订单变更及历史融资记录
         * @arg 参数orderId为订单Id
		*/
		getOrderChangeData (orderId) {
			let params = {
				custId: this.custInf.custId,
				orderId: orderId
			}
			return new Promise((resolve, reject) => {
				this.$http.reviewOrderChange(params).then(({ data }) => {
					if (data.code == 200) {
						resolve(data.rows)
					} else {
						reject(data.info)
					}
				}).catch(err => {
					reject('获取数据失败!')
				})
			})
		},
        /**
		 * @vuese
		 * 获取申请单退回信息
         * @arg 参数applyIdd为当前申请单Id
		*/
		async getRefusedActivity (applyId) {
			await this.$http.getRefusedActivity({
				applyId: applyId
			}).then(({ data }) => {
				if (data.code == 200 && data.rows) {
					this.returnReason = data.rows.note || ''
				}
			}).catch(error => {
				this.$alert("查询退回信息数据失败，请检查网络！", {
					confirmButtonText: "确定",
					customClass: "alertFailure"
				})
			})
		},
        /**
		 * @vuese
		 * 获取当前账户电子签信息
		*/
		async getEsignAccountByCustId () {
			let custId = this.supplyChainFinance.custInf.custId + ""
			let that = this
			await this.$http.getEsignAccountByCustId({
				custId: custId
			}).then(({
				data
			}) => {
				if (data.code == 200 && data.rows) {
					that.bankNo = data.rows.bank_no
					var bankinfo = data.rows.sub_bank
					bankinfo = bankinfo.replace(data.rows.bank, '')
					bankinfo = data.rows.bank + bankinfo
					that.bank = bankinfo
					that.name = data.rows.name
				} else {
					this.$alert(`获取数据失败：${data.info}`, {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					})
				}
			}).catch(error => {
				this.$alert('查询失败，请检查网络！', {
					confirmButtonText: "确定",
					customClass: "alertFailure"
				})
			})
		},
        /**
		 * @vuese
		 * 点击返回按钮回调
		*/
		goBack () {
			if (this.fromPage == "deliveryFinancePreview") {
				//从订单融资页面跳转
				this.$emit("showShotPreview", this.applyId);
			} else if (this.fromPage == 'applyList') {
				this.changePageCode('')
			}
			this.listArray = [];
		},
        /**
		 * @vuese
		 * 提交金单宝或者金货宝申请流程
		*/
		submit () {
			let loading;
			if (this.applyRowData.length == 0) {
				this.$alert("请添加订单", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			} else if (!this.applyShortTableForm.apply_date) {
				this.$alert("融资开始日期不能为空!", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			} else if (this.currentMoney < this.applyShortTableForm.apply_amt) {
				this.$alert("关联订单的可融资金额小于本次申请的融资金额,请重新选择!", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			} else if (!this.applyShortTableForm.prepayback_date) {
				this.$alert("融资到期日期不能为空!", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			}
			this.$confirm('确认是否提交申请表?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消'
			}).then(() => {
				loading = this.$loading({
					lock: false,
					text: '融资申请提交中，请稍等',
					spinner: 'el-icon-loading',
					background: 'rgba(255,255,255,.9)'
				})
				if (this.mode == 'order') {
					this.submitOrderFin().then(_ => {
						loading.close()
						this.isSign = true;
						this.applyIdFromCommit = this.applyShortTableForm.id;
						this.finType = '2'
						this.listArray = []
						Msg.showSuccessMsg('融资申请提交成功!')
					}).catch(err => {
						loading.close()
						Msg.showErrorMsg(err)
					})
				} else if (this.mode == 'delivery') {
					this.submitDelivery().then(_ => {
						loading.close()
						this.isSign = true;
						this.applyIdFromCommit = this.applyShortTableForm.id;
						this.listArray = []
						this.finType = '3'
						Msg.showSuccessMsg('融资申请提交成功!')
					}).catch(err => {
						loading.close()
						Msg.showErrorMsg(err)
					})
				}
			}).catch(() => { })
		},
        /**
		 * @vuese
		 * 提交金货宝申请
		*/
		submitDelivery () {
			const { id, apply_amt, prepayback_date, apply_date, service_rate, availableAmt } = this.applyShortTableForm
			let params = {
				applyId: id, //申请Id
				availableAmt, //可融金额
				rate: 0, //利率为0
				applyAmt: apply_amt, //申请融资金额
				applyDate: `${apply_date} 00:00:00`, //融资到期日期
				prepaybackDate: `${prepayback_date} 00:00:00`, //融资到期日期
				serviceRate: service_rate, //服务利率
				applyOrders: [],//订单集合
			}
			this.applyRowData.forEach(row => {
				params.applyOrders.push({
					applyId: id,          //申请单ID
					orderNo: row.purOrdNo, //订单编号
					actBalance: row.actBalance, //本次融资金额
					financingStatus: row.financingStatus,//融资状态
					finBalance: row.meltedAmount,//在融金额
					borrowBalance: row.availableAmount,//可融金额
					orderBalance: row.orderAmount,//订单金额
					instockBalance: row.deliveryAmount,//订单入库金额
					appointmentDate: row.earliestDeliveryDate,//最早交货日期
					orderDate: row.purOrdDate,//订单日期
					contractNo: row.contractNo, //合同编号
					contractName: row.contractName, //合同名称
					companyName: row.companyName,//公司名称
					companyCode: row.companyCode //公司编码
				})
			})
			return new Promise((resolve, reject) => {
				this.$http.submitApplyDeliveryFince(params).then(({ data }) => {
					if (data.code == 1) {
						resolve()
					} else {
						reject(data.info)
					}
				}).catch(err => {
					reject('提交金货宝申请失败!')
				})
			})
		},
		/**
		 * @vuese
		 * 提交金单宝申请
		*/
		submitOrderFin () {
			const { id, apply_amt, prepayback_date, apply_date, service_rate, availableAmt } = this.applyShortTableForm
			let params = {
				id, //申请Id
				sumBorrowBalance: availableAmt, //可融金额
				rate: 0, //利率为0
				applyAmt: apply_amt, //申请融资金额
				applyDate: `${apply_date} 00:00:00`, //融资到期日期
				prepaybackDate: `${prepayback_date} 00:00:00`, //融资到期日期
				serviceRate: service_rate, //服务利率
				finType: 2,
				entityList: [],//订单集合
			}
			this.applyRowData.forEach(row => {
				params.entityList.push({
					applyId: id,
					id: row.orderId,
					orderNo: row.orderNumber, //订单编号
					actBalance: row.actBalance, //本次融资金额
					// financingStatus: row.financingStatus,//融资状态
					finBalance: row.alreadyActBalance,//在融金额
					borrowBalance: row.borrowBalance,//可融金额
					orderBalance: row.orderMoney,//订单金额
					appointmentDate: row.oldestDeliveryDate,//最早约定交货日期
					orderDate: row.orderDate,//订单日期
					contractNo: row.contractNo, //合同编号
					contractName: row.contractName, //合同名称
					companyName: row.companyName,//公司名称
					companyCode: row.companyCode //公司编码
				})
			})
			return new Promise((resolve, reject) => {
				this.$http.submitOrderFinApply(params).then(({ data }) => {
					if (data.code == 1 || data.code == 200) {
						resolve()
					} else {
						reject(data.info)
					}
				}).catch(err => {
					reject('提交金单宝申请失败!')
				})
			})
		},
        /**
		 * @vuese
		 * 点击添加按钮回调打开选择订单弹窗
		*/
		addLetter () {
			this.assemblyModel = true;
			this.searchValue = ''
			this.isSearch = false
			if (this.mode == 'delivery') {
				this.getApplyOrderList({
					supplierId: this.custInf.custId,
					flag: this.orderState,
					filterAmountFlag: 1
				});
			} else {
				this.getOrderFinceOrderList()
			}
		},
        /**
		 * @vuese
		 * 调接口获取金单宝可融资订单列表数据
		*/
		getOrderFinceOrderList () {
			let params = {
				supplierId: this.custInf.custId,
				state: this.orderState
			}
			this.checkingLoading = true
			this.checkingRowData = [];
			this.$http.getAvaildOrderList(params).then(({ data }) => {
				this.checkingLoading = false;
				if (data.code == 1) {
					let rowDatas = data.rows;
					this.checkingRowData = rowDatas;
					if (this.isSearch && this.checkingRowData.length == 0) {
						this.checkingGridOptions.overlayNoRowsTemplate = '未搜索到匹配结果'
					}
					// 可融资金额小于0,不可选择
					this.$nextTick(_ => {
						this.checkingGridOptions.api.forEachNode(function (node) {
							if (node.data.borrowBalance === 0 || node.data.borrowBalance < 0) {
								node.selectable = false
							}
						})
					})
				} else {
					this.checkingRowData = [];
					if (this.isSearch) {
						this.checkingGridOptions.overlayNoRowsTemplate = '未搜索到匹配结果'
					}
				}
			}).catch(err => {
				Msg.showErrorMsg('查询订单列表数据失败!')
			})
		},
		/**
		 * @vuese
		 * 添加订单弹窗搜索订单
		*/
		searchLetter () {
			let params = {
				supplierId: this.custInf.custId,
				flag: this.orderState,
				filterAmountFlag: 1
			}
			this.isSearch = true
			if (this.mode == 'order') {
				this.getOrderFinceOrderList()
			} else {
				this.getApplyOrderList(params);
			}
		},
		/**
		 * @vuese
		 * 删除已选择关联订单数据
		*/
		delLetter () {
			let selectRows = this.applyGridOptions.api.getSelectedRows();
			if (selectRows.length == 0) {
				this.$alert("请选择你要删除的订单", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			}
			let originRows = JSON.parse(JSON.stringify(this.applyRowData));
			const { apply_amt } = this.applyShortTableForm
			let money = 0
			let delRowData = this.delSelectRows(selectRows, originRows)
			let promitMsg = ""
			if (delRowData.length == 0) {
				this.$confirm("是否确认删除全部已关联订单?", '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: 'msg-hint',
					center: false
				}).then(_ => {
					this.applyRowData = delRowData
					this.applyShortTableForm.prepayback_date = '' //订单为空重置融资到期日期为空
					this.showAddBtn = true
				}).catch(_ => {
					console.log('已取消')
				})
			} else {
				if (this.mode == 'order') {
					delRowData.forEach(item => {
						money += item.borrowBalance
					})
				} else {
					delRowData.forEach(item => {
						money += item.availableAmount
					})
				}
				if (money < apply_amt) {
					promitMsg = "删除后订单的可融资金额小于申请融资金额,需添加新的订单,是否确认删除?"
				} else {
					promitMsg = "删除后订单的可融资金额仍可满足当前融资需求,无需添加新的订单,是否确认删除?"
				}
				this.currentMoney = money
				this.$confirm(promitMsg, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: 'msg-hint',
					center: false
				}).then(_ => {
					if (money > apply_amt) {
						if (this.mode == 'delivery') {
							this.applyRowData = this.currentFinAmount(delRowData, 'earliestDeliveryDate', 'availableAmount', 'purOrdDate')
						} else {
							this.applyRowData = this.currentFinAmount(delRowData, 'oldestDeliveryDate', 'borrowBalance', 'orderDate')
						}
						this.showAddBtn = false
					} else {
						this.applyRowData = delRowData
						this.showAddBtn = true
					}
					this.getFinancEndDate(this.applyRowData) //重新计算融资到期日期
				}).catch(_ => {
					console.log('已取消')
				})
			}
			// this.applyRowData = this.delSelectRows(selectRows, originRows);
		},
        /**
		 * @vuese
		 * 选择订单时对已选择订单进行排序
         * @arg 参数arrData已选择订单数组;property为排序属性;orderDate为订单日期
		*/
		sortSelectRows (arrData, property, orderDate) {
			let sortArr = []
			function compare (propert) {
				return (a, b) => {
					let value1 = Date.parse(a[propert])
					let value2 = Date.parse(b[propert])
					if (value1 == value2) {
						return a[orderDate] - b[orderDate]
					}
					return value1 - value2
				}
			}
			// 按交货日期进行排序
			sortArr = arrData.sort(compare(property))
			return sortArr
		},
        /**
		 * @vuese
		 * 按最早交货/约定交货日期分配本次融资金额
         * @arg 参数arrData已选择订单数组;property为排序属性;amount可融资金额
		*/
		currentFinAmount (arrData, property, amount, orderDate) {
			// 按照最早交货日期进行排序,最早交货日期相同时按订单日期排序
			let money = this.applyShortTableForm.apply_amt
			function compare (propert) {
				return (a, b) => {
					let value1 = Date.parse(a[propert])
					let value2 = Date.parse(b[propert])
					if (value1 == value2) {
						return a[orderDate] - b[orderDate]
					}
					return value1 - value2
				}
			}
			// 按交货日期进行排序
			arrData.sort(compare(property))
			// 依次扣除可融金额
			arrData.forEach(item => {
				money -= item[amount]
				if (money > 0) {
					item.actBalance = item[amount]
				} else {
					item.actBalance = item[amount] + money
				}
			})
			return arrData
		},
        /**
		 * @vuese
		 * 确认添加已选择的订单
		*/
		saveLetter () {
			let selectRows = this.checkingGridOptions.api.getSelectedRows();
			if (selectRows <= 0) {
				this.$alert("请选择需要关联的订单进行保存", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			}
			if (this.applyRowData.length > 0) {
				let uniqueNo = []
				this.applyRowData.forEach(row => {
					selectRows.forEach(sel => {
						let property = this.mode == 'order' ? 'orderNumber' : 'purOrdNo'
						if (sel[property] === row[property]) {
							uniqueNo.push(row[property])
						}
					})
				})
				if (uniqueNo.length > 0) {
					Msg.showPopMsg(`已添加的订单中已存在订单号为${uniqueNo.join('、')}的订单，请重新选择!`)
					return
				} else {
					selectRows = this.unique([...selectRows, ...this.applyRowData])
				}
			}
			let letterArr = []
			//系统自动分配订单融资金额
			let letters = []
			let ishint = false
			//订单可融金额总数
			let letterMoney = 0
			//融资金额
			let money = this.applyShortTableForm.apply_amt
			if (this.mode == 'delivery') {
				selectRows = this.sortSelectRows(selectRows, 'earliestDeliveryDate', 'purOrdDate')
				for (let i = 0; i < selectRows.length; i++) {
					if (money > letterMoney) {
						letterMoney += selectRows[i].availableAmount
						letterArr.push(selectRows[i].purOrdNo)
						letters.push(selectRows[i])
					} else {
						ishint = true
						break
					}
				}
				letters = this.currentFinAmount(letters, 'earliestDeliveryDate', 'availableAmount', 'purOrdDate')
			} else if (this.mode == 'order') {
				selectRows = this.sortSelectRows(selectRows, 'oldestDeliveryDate', 'orderDate')
				for (let i = 0; i < selectRows.length; i++) {
					if (money > letterMoney) {
						letterMoney += selectRows[i].borrowBalance
						letterArr.push(selectRows[i].orderNumber)
						letters.push(selectRows[i])
					} else {
						ishint = true
						break
					}
				}
				letters = this.currentFinAmount(letters, 'oldestDeliveryDate', 'borrowBalance', 'orderDate')
			}
			if (money > letterMoney) {
				this.$alert("您选择的订单可融金额小于申请融资金额，请继续添加订单", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			}
			this.currentMoney = letterMoney
			this.showAddBtn = false
			if (ishint) {
				this.$confirm(`经系统计算，您选择的订单中只需选择 ${letterArr.join('、')} 即可满足当前融资需求，同意系统自动分配,请点击“确认”，如需重新选择，请点击“取消”`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: 'msg-hint',
					center: false
				}).then(() => {
					this.applyRowData = []
					this.listArray = this.applyRowData.concat(letters); //数组合并
					this.getFinancEndDate(this.unique(this.listArray))
					// 融资到期日期不为空时
					if (this.applyShortTableForm.prepayback_date) {
						this.applyRowData = this.unique(this.listArray);
						this.checkingRowData = []; //清空弹窗数据
						this.assemblyModel = false;
					} else {
						Msg.showPopMsg("根据系统计算已选择订单的可融天数为0,请重新选择!")
						this.applyRowData = []
					}
				}).catch(() => { })
			} else {
				this.applyRowData = []
				this.listArray = this.applyRowData.concat(letters); //数组合并
				this.getFinancEndDate(this.unique(this.listArray))
				// 融资到期日期不为空时
				if (this.applyShortTableForm.prepayback_date) {
					this.applyRowData = this.unique(this.listArray);
					this.checkingRowData = []; //清空弹窗数据
					this.assemblyModel = false;
				} else {
					Msg.showPopMsg("根据系统计算已选择订单的可融资天数为0,请重新选择!")
					this.applyRowData = []
				}
			}
		},
        /**
		 * @vuese
		 * 计算最大融资到期日期
         * @arg 参数rowDate为已选择订单;n;
		*/
		getFinancEndDate (rowDate, n) {
			let deliveryDates = []
			if (this.mode == 'delivery') {
				deliveryDates = rowDate.map(item => {
					return new Date(item.earliestDeliveryDate)
				})

			} else if (this.mode == 'order') {
				deliveryDates = rowDate.map(item => {
					return new Date(item.oldestDeliveryDate)
				})
			}
			let minDate = (...dates) => new Date(Math.min.apply(null, ...dates)) //获取最小时间
			let minMonth = minDate(deliveryDates).getMonth() + 1
			let minYear = minDate(deliveryDates).getFullYear()
			if (minMonth == 12) {
				// this.applyShortTableForm.prepayback_date = `${Number(minYear) + 1}-01-25`
				this.getPrepaybackDate(minYear + 1, '01', 25)
			} else {
				// this.applyShortTableForm.prepayback_date = `${minYear}-${Number(minMonth) + 1}-25`
				this.getPrepaybackDate(minYear, minMonth + 1, 25)
			}
			if (this.currentAct == '供应商发起融资') {
				if (this.applyShortTableForm.prepayback_date) this.startDateReadeOnly = false
			} else {
				this.startDateReadeOnly = true
				this.endDateReadeOnly = true
			}
		},
		/**
		 * @vuese
		 * 控制融资日期范围为工作日，非工作日提前
         * @arg 参数year为当前年;month为当前月;day为最大可选择日
		*/
		getPrepaybackDate (year, month, day) {
			let year1 = year
			let month1 = month
			let date = new Date(`${year1}-${month1}-${day}`)
			let dateFormat = this.$utils.dateFormat;
			if (!this.datePickerOptions(date, dateFormat('yyyy-MM-dd', date), false) && date.getTime() > new Date().getTime()) {
				this.applyShortTableForm.prepayback_date = dateFormat('yyyy-MM-dd', date)
				this.maxEndDate = dateFormat('yyyy-MM-dd', date)
				this.endDateReadeOnly = false
			} else {
				if (date.getTime() > new Date().getTime()) {
					this.getPrepaybackDate(year1, month1, day - 1)
				} else {
					this.applyShortTableForm.prepayback_date = ''
					this.endDateReadeOnly = true
				}
			}
		},
        /**
		 * @vuese
		 * 获取金货宝实时订单列表
         * @arg 参数params为Obj类型,代表接口请求参数;
		*/
		getApplyOrderList (params) {
			let that = this;
			that.checkingLoading = true
			that.checkingRowData = [];
			that.checkingGridOptions.overlayNoRowsTemplate = '&nbsp;'
			setTimeout(function () {
				that.$http.getDeliveryOrderList(params).then(response => {
					that.checkingLoading = false;
					if (response.data.code == 1) {
						let rowDatas = response.data.rows;
						that.checkingRowData = rowDatas;
						if (that.isSearch && that.checkingRowData.length == 0) {
							that.checkingGridOptions.overlayNoRowsTemplate = '未搜索到匹配结果'
						}
						// 融资金额为0,不可选择
						that.$nextTick(_ => {
							that.checkingGridOptions.api.forEachNode(function (node) {
								if (node.data.availableAmount === 0 || node.data.availableAmount < 0) {
									node.selectable = false
								}
							})
						})
					} else {
						that.checkingRowData = [];
						if (that.isSearch) {
							that.checkingGridOptions.overlayNoRowsTemplate = '未搜索到匹配结果'
						}
					}
				})
					.catch(errror => {
						that.$alert("查询订单列表失败，请检查网络！", {
							confirmButtonText: "确定",
							customClass: "alertFailure"
						});
					});
			}, 500);
		},
        /**
		 * @vuese
		 * 删除已添加的订单行
         * @arg 参数selectArrayData为已选择的需要删除的订单,originArrayData所有已选择的订单;
		*/
		delSelectRows (selectArrayData, originArrayData) {
			selectArrayData.forEach((item) => {
				originArrayData.forEach((sel, index) => {
					if (this.mode == 'order') {
						if (sel.orderNumber === item.orderNumber) {
							originArrayData.splice(index, 1)
						}
					} else {
						if (sel.purOrdNo === item.purOrdNo) {
							originArrayData.splice(index, 1)
						}
					}
				})
			})
			return originArrayData;
		},
		/**
		* @vuese
		* 数组去重
		* @arg 参数objArray为数组,代表需要去重的数组;
	   */
		unique (objArray) {
			var result = [];
			var temp = {};
			for (var i = 0; i < objArray.length; i++) {
				var myid = this.mode == "delivery" ? objArray[i].purOrdNo : objArray[i].orderNumber;
				if (temp[myid]) {
					continue;
				}
				temp[myid] = true;
				result.push(objArray[i]);
			}
			return result;
		},
	},
	computed: {
		...mapState(['supplyChainFinance', 'supplierApplyList']),
		// 融资到期日说明
		tagContent () {
			if (this.mode == 'order') {
				return '融资到期日期最大为本次融资订单里物料最早约定交货日期计算到次月25号,25号非工作日提前!'
			} else {
				return '融资到期日期最大为本次融资使用订单已交货里物料最早的入库日期计算,到次月的25号,25号非工作日提前!'
			}
		},
		// 融资费率说明
		gridData () {
			let tableData = []
			if (this.mode == 'order') {
				tableData = [
					{ rate: '0.05%/天', date: '0-30天' },
					{ rate: '0.04%/天', date: '30-60天' },
					{ rate: '0.035%/天', date: '60-90天' },
				]
			} else {
				tableData = [
					{ rate: '0.04%/天', date: '0-15天' },
					{ rate: '0.035%/天', date: '15-30天' },
					{ rate: '0.03%/天', date: '30天以上' },
				]
			}
			return tableData
		},
		//显示服务费率
		showRate () {
			const { service_rate } = this.applyShortTableForm
			return formatRate(service_rate) + "/天";
		},
		//获取预扣金额
		getPreDeductAmount () {
			this.applyShortTableForm.preDeductAmount = numberMul(numberMul(this.applyShortTableForm.apply_amt, this.showRate), this.applyShortTableForm.dayAmount).toFixed(2)
			return formatPrice(this.applyShortTableForm.preDeductAmount);
		},
		// 获取实际到账金额
		getArrivalAmount () {
			this.applyShortTableForm.arrivalAmount = numberSub(this.applyShortTableForm.apply_amt, this.applyShortTableForm
				.preDeductAmount).toFixed(2)
			return formatPrice(this.applyShortTableForm.arrivalAmount);
		},
		// 获取融资天数
		getDayAmount () {
			const { apply_date, prepayback_date } = this.applyShortTableForm
			this.applyShortTableForm.dayAmount = dateDiff(
				apply_date,
				prepayback_date
			);
			return this.applyShortTableForm.dayAmount + "天";
		},
		//获取融资到期日
		getPaybackDate () {
			return getSpecifyDate(25);
		},
		isSubmitApplyTable () {
			return this.currentAct == '联塑金融审批' || this.currentAct == '已完成' || this.currentAct == '已退回' || this.currentAct == '已撤销' || this.currentAct == '供应商还款'
		},
		// 获取融资金额
		getFormatApplyAmt () {
			return formatPrice(this.applyShortTableForm.apply_amt)
		},
		// 融资开始日期限制
		pickerOptionsBegin () {
			let dateFormat = this.$utils.dateFormat
			let prepaybackDate = this.applyShortTableForm.prepayback_date //融资到期日期
			let nowDate = new Date().getTime() - 24 * 60 * 60 * 1000;
			let that = this
			return {
				disabledDate (time) {
					//开始日期不可大于融资到期日期 并且 开始日期不可小于当前日期
					if (prepaybackDate && time.getTime() > new Date(`${prepaybackDate} 00:00:00`).getTime() || time < new Date(nowDate)) {
						return true
					}
					return that.datePickerOptions(time, dateFormat('yyyy-MM-dd', time), true)
				}
			}
		},
		// 融资到期日期限制
		pickerOptionsEnd () {
			let dateFormat = this.$utils.dateFormat
			let applyDate = this.applyShortTableForm.apply_date //融资到期日期
			let that = this
			return {
				disabledDate (time) {
					//融资到期日期不可小于融资开始日期 并且 到期日期不可大于最大到期日期
					if (applyDate && time.getTime() < new Date(`${applyDate} 00:00:00`).getTime() || time > new Date(`${that.maxEndDate} 00:00:00`)) {
						return true
					}
					return that.datePickerOptions(time, dateFormat('yyyy-MM-dd', time), true)
				}
			}
		},
	},
	watch: {
		'applyShortTableForm.apply_date': {
			handler (newVal, oldVal) {
				const { prepayback_date } = this.applyShortTableForm
				this.applyShortTableForm.dayAmount = dateDiff(
					newVal,
					prepayback_date
				)
				const { dayAmount } = this.applyShortTableForm
				if (this.mode == 'order') {
					if (dayAmount > 90) {
						Msg.showPopMsg('融资日期最多为90天')
						this.applyShortTableForm.apply_date = ''
					} else if (dayAmount > 0 && dayAmount < 31) {
						this.applyShortTableForm.service_rate = 0.0005
					} else if (dayAmount > 30 && dayAmount < 61) {
						this.applyShortTableForm.service_rate = 0.0004
					} else if (dayAmount > 60 && dayAmount < 91) {
						this.applyShortTableForm.service_rate = 0.00035
					} else {
						this.applyShortTableForm.service_rate = 0
					}
				} else if (this.mode == 'delivery') {
					if (dayAmount > 90) {
						Msg.showPopMsg('融资日期最多为90天')
						this.applyShortTableForm.apply_date = ''
					} else if (dayAmount > 0 && dayAmount < 16) {
						this.applyShortTableForm.service_rate = 0.0004
					} else if (dayAmount > 16 && dayAmount < 31) {
						this.applyShortTableForm.service_rate = 0.00035
					} else if (dayAmount > 30) {
						this.applyShortTableForm.service_rate = 0.0003
					} else {
						this.applyShortTableForm.service_rate = 0
					}
				}
			},
			immediate: true
		},
		'applyShortTableForm.prepayback_date': {
			handler (newVal, oldVal) {
				const { apply_date } = this.applyShortTableForm
				this.applyShortTableForm.dayAmount = dateDiff(
					apply_date,
					newVal
				)
				const { dayAmount } = this.applyShortTableForm
				if (this.mode == 'order') {
					if (dayAmount > 90) {
						Msg.showPopMsg('融资日期最多为90天')
						this.applyShortTableForm.apply_date = ''
					} else if (dayAmount > 0 && dayAmount < 31) {
						this.applyShortTableForm.service_rate = 0.0005
					} else if (dayAmount > 30 && dayAmount < 61) {
						this.applyShortTableForm.service_rate = 0.0004
					} else if (dayAmount > 60 && dayAmount < 91) {
						this.applyShortTableForm.service_rate = 0.00035
					} else {
						this.applyShortTableForm.service_rate = 0
					}
				} else if (this.mode == 'delivery') {
					if (dayAmount > 90) {
						Msg.showPopMsg('融资日期最多为90天')
						this.applyShortTableForm.apply_date = ''
					} else if (dayAmount > 0 && dayAmount < 16) {
						this.applyShortTableForm.service_rate = 0.0004
					} else if (dayAmount > 16 && dayAmount < 31) {
						this.applyShortTableForm.service_rate = 0.00035
					} else if (dayAmount > 30) {
						this.applyShortTableForm.service_rate = 0.0003
					} else {
						this.applyShortTableForm.service_rate = 0
					}
				}
			},
			immediate: true
		},
		'applyShortTableForm.dayAmount': {
			handler (newVal, oldVal) {
				let preDeductAmount = numberMul(numberMul(this.applyShortTableForm.apply_amt, this.applyShortTableForm.service_rate), newVal).toFixed(2)
				this.applyShortTableForm.preDeductAmount = formatPrice(preDeductAmount);
				let arrivalAmount = numberSub(this.applyShortTableForm.apply_amt, preDeductAmount).toFixed(2)
				this.applyShortTableForm.arrivalAmount = formatPrice(arrivalAmount);
			},
			immediate: true
		},
	},
	components: {
		Pagination,
		signPreview,
		buttonLink
	}
};
</script>